/*
 * #%L
 * SwiftUIWeb Maven Webapp
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
package com.linkwithweb.products.swiftui.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.linkwithweb.products.swiftui.context.ExcelFile;
import com.linkwithweb.products.swiftui.context.SystemContext;
import com.linkwithweb.products.swiftui.dataobject.FrameworkUpload;
import com.linkwithweb.products.swiftui.model.UploadBean;
import com.linkwithweb.products.swiftui.service.PlatformService;
import com.linkwithweb.swiftui.messaging.SwiftUIMessageProducer;

/**
 * @author ashwin kumar
 * 
 */
@Controller
@RequestMapping("/upload")
public class FileUploadController extends AbstractController {
	private static final String DESTINATION_DIR_PATH = "/data/tomcat/";

	@Autowired
	@Qualifier("platformService")
	private PlatformService platformService;

	@Autowired
	@Qualifier("swiftUIMessageProducer")
	private SwiftUIMessageProducer swiftUIMessageProducer;

	/**
	 * Constructor
	 */
	public FileUploadController() {
	}

	/**
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		model.addAttribute("uploadbean", new UploadBean());
		return "home";
	}

	/**
	 * @param request
	 * @param uploadbean
	 * @param result
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public String uploadFiles(HttpServletRequest request,
			HttpServletResponse response) {
		System.out.println("started uploading");

		if (!(request instanceof org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest)) {
			return "forms/success";
		}

		org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest multiPartRequest = (org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest) request;
		String uploadedFileName = ((org.springframework.web.multipart.commons.CommonsMultipartFile) (multiPartRequest.getFileMap().values()
				.toArray()[0])).getOriginalFilename();
		String fileKey = multiPartRequest.getFileMap().keySet().toArray(new String[0])[0];

		// Some type of file processing...
		System.err.println("-------------------------------------------");

		System.err.println("Uploading file: " + uploadedFileName);
		System.err.println("-------------------------------------------");
		String fileName = getUniqueString() + "_" + uploadedFileName;
		String basePath = "";
		try {
			File destinationDir = null;

			basePath = System.getProperty("user.dir");
			if (StringUtils.equalsIgnoreCase(
					multiPartRequest.getParameter("uploadType"), "TEMPLATE")) {
				destinationDir = new File(basePath + "/customuploads/");
			} else {
				destinationDir = new File(basePath + "/fileuploads/");
			}

			if (!destinationDir.exists()) {
				destinationDir.mkdirs();
			}

			File file = new File(destinationDir, fileName);
			String path = file.getAbsolutePath();
			final String currentContextPath = request.getContextPath();
			// uploadbean.getFiledata().transferTo(file);

			multiPartRequest.getFile(fileKey).transferTo(file);

			if (StringUtils.containsIgnoreCase(path, "customuploads")) {
				FrameworkUpload frameworkUpload = new FrameworkUpload();
				frameworkUpload.setUploadDesc(fileName);
				frameworkUpload.setUploadId(fileName);
				frameworkUpload
						.setUploadLabel(uploadedFileName.split("\\.")[0]);
				frameworkUpload.setUploadTag(","
						+ multiPartRequest.getParameter("fileType"));
				frameworkUpload.setUploadPath(file.getAbsolutePath());
				frameworkUpload.setUploadType(multiPartRequest
						.getParameter("uploadType"));

				try {
					getPlatformService().uploadFile(frameworkUpload);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return "forms/success";
			}

			ExcelFile excelFile = new ExcelFile();
			excelFile.setTableName("");
			excelFile.setSchemaName("");
			excelFile.setFileName(file.getName());
			excelFile.setFilePath(file.getAbsolutePath());
			excelFile.setExcelType(multiPartRequest.getParameter("fileType"));
			excelFile
					.setUploadType(multiPartRequest.getParameter("uploadType"));

			Map<String, Object> data = new HashMap<String, Object>();
			data.put("excelFile", excelFile);
			data.put("userContext", SystemContext.getInstance()
					.getUserContext());

			/**
			 * Now call File processing in Async Mode
			 */
			swiftUIMessageProducer.sendAsyncRequest(SystemContext.getInstance().getClientName().get(), "FILE_UPLOAD", data);
			// getPlatformService().loadExcelFile(excelFile);

			// file.delete();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}

		/**
		 * Now start loading Data into server
		 */

		return "forms/success";
	}
}